package com.demo.dialet;

import org.springframework.jdbc.core.JdbcTemplate;


public class PaginationSupport {

	private static final ThreadLocal<PageLimit> threadLocal = new ThreadLocal();
	
	public static PageLimit getContext() {
		return (PageLimit) threadLocal.get();
	}

	@Deprecated
	public static void setContext(Integer currentPageNo, Integer pageLength, Integer totalCount) {
		threadLocal.set(new PageLimit(currentPageNo, pageLength, totalCount));
	}
	
	public static void byPage(Integer currentPageNo, Integer pagSize) {
		threadLocal.set(new PageLimit(currentPageNo, pagSize, null));
	}
	
	public static void byPage(Integer currentPageNo, Integer pagSize,boolean count) {
		threadLocal.set(new PageLimit(currentPageNo, pagSize, null,count));
	}
	
	public static void byStart(Integer startRowNo, Integer pagSize) {
		threadLocal.set(new PageLimit(startRowNo,pagSize));
	}
	
	public static void byStart(Integer startRowNo, Integer pagSize,boolean count) {
		threadLocal.set(new PageLimit(startRowNo,pagSize,count));
	}
	
	public static void byId(Integer pageSize, String id){
		if (id != null && id.length() == 0) id = null;
		threadLocal.set(new PageLimit(pageSize,id));
	}
	
	public static void byId(Integer pageSize, String id, String name){
		if (id != null && id.length() == 0) id = null;
		threadLocal.set(new PageLimit(pageSize,id,name));
	}
	
	public static void getTotal() {
		threadLocal.set(new PageLimit());
	}
	//初始化总记录数
	public static String initPage(String sql,JdbcTemplate jdbcTemplate){
		int c = jdbcTemplate.queryForObject("select count(1) from ("+ sql+") a_cnt", Integer.class);
		PaginationSupport.getContext().setTotalCount(c);
		sql+=" limit "+(PaginationSupport.getContext().getStartRowNo()-1)+","+PaginationSupport.getContext().getPageLength();
		return sql;
	}
	
}
